package org.jeecg.modules.cascv.rabbitmq;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.cascv.image.util.LaptopConstant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author;作者
 * @Date 2023/6/15 10:34
 * @Description :
 * @Version
 */
@Component
@Slf4j
public class FileTimetask {
    private String FILE_PATH = "\\data\\jsonfile\\";
    private String FILE_SUFFIX = ".json";

    @Autowired
    private RabbimtMQListener rabbimtMQListener;
////fixedDelay
   @Scheduled(fixedDelay = 3000)
    public void writeDataToFile() {

            List<String> jsonDataList = rabbimtMQListener.getJsonDataList();

        if (jsonDataList.isEmpty()) {
                return;
                }

                String listsize = String.valueOf(jsonDataList.size());

                String idsName = getIdsNameFromJson(jsonDataList.get(0));
                String lastsize = LaptopConstant.lastlistsize.get(idsName);

                if (StringUtils.isEmpty(lastsize)){
                LaptopConstant.lastlistsize.put(idsName,listsize);
                return;
                }else if (lastsize.equals(listsize)){

                String time = getCurrentDateTime();
                String fileName = idsName + "_" + time + FILE_SUFFIX;
                String filePath = FILE_PATH + fileName;

                log.info("实时播放开始写入文件,文件地址为"+filePath);
                try {
                for (String jsonStr : jsonDataList) {
                //  log.info("接收数据中==>"+jsonStr);
                FileUtil.appendUtf8String(jsonStr + System.lineSeparator(),
                filePath);
                }

                } catch (Exception e) {
                log.error("数据添加失败：", e);
                }
                log.info("实时播放写入文件结束，文件地址为："+filePath);
                rabbimtMQListener.getJsonDataList().clear();
                LaptopConstant.lastlistsize.remove(idsName);

                }else {
                LaptopConstant.lastlistsize.put(idsName,listsize);
                return;
                }
    }


    private String getIdsNameFromJson(String jsonData) {
        // 从JSON数据中获取idsname
        jsonData = jsonData.substring(14, 23);
        return jsonData;
    }

    private String getCurrentDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date());
}
}
















//